package com.nimitz.module.employee.service.impl;

import com.nimitz.common.annotation.DataScope;
import com.nimitz.common.utils.SecurityUtils;
import com.nimitz.module.employee.domain.EmpEmployee;
import com.nimitz.module.employee.domain.EmpOfficial;
import com.nimitz.module.employee.mapper.EmpEmployeeMapper;
import com.nimitz.module.employee.mapper.EmpOfficialMapper;
import com.nimitz.module.employee.service.IEmpOfficialService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 转正 业务层实现
 */
@Service
public class EmpOfficialServiceImpl implements IEmpOfficialService {

    @Resource
    private EmpOfficialMapper officialMapper;
    @Resource
    private EmpEmployeeMapper employeeMapper;

    /**
     * 根据入职id查询入职
     *
     * @param officialId 入职id
     * @return 入职
     */
    @Override
    public EmpOfficial selectOfficialById(Integer officialId) {
        return officialMapper.selectOfficialById(officialId);
    }

    /**
     * 根据条件查询入职列表（含分页）
     *
     * @param official 入职
     * @return 入职集合
     */
    @Override
    @DataScope(deptAlias = "tn1")
    public List<EmpOfficial> selectOfficialList(EmpOfficial official) {
        return officialMapper.selectOfficialList(official);
    }

    /**
     * 批量审核
     *
     * @param updateBy    更新者
     * @param officialIds 入职ID集合
     * @return 结果
     */
    @Override
    @Transactional
    public int auditOfficial(String updateBy, Integer[] officialIds) {
        int returnVal = officialMapper.auditOfficial(updateBy, officialIds);
        if (returnVal > 0) {
            // 根据officialIds获取集合
            List<EmpOfficial> officialList = officialMapper.selectOfficialByIds(officialIds);
            // 生成人员记录集合
            List<EmpEmployee> employeeList = new ArrayList<>();
            for (EmpOfficial official : officialList) {
                EmpEmployee employee = new EmpEmployee();
                employee.setEmployeeId(official.getEmployeeId());
                employee.setDeptId(official.getOfficialEmployee().getDeptId());
                employee.setEmployeeConfirmationDate(official.getOfficialDate());
                employee.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
                employeeList.add(employee);
            }
            // 批量修改人员转正日期
            employeeMapper.updateEmployeeByList(employeeList);
        }
        return returnVal;
    }
}
